package com.stu.stusystem.controller.system;

import com.stu.stusystem.common.ApiException;
import com.stu.stusystem.common.ApiResult;
import com.stu.stusystem.model.system.Document;
import com.stu.stusystem.service.system.DocumentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import liquibase.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author: cxt
 * @time: 2021/6/24
 */
@Api(tags = "文件管理")
@RestController
@EnableScheduling
@RequestMapping("/document")
public class DocumentController {

    private DocumentService documentService;

    @ApiOperation("formData格式")
    @PostMapping("/formData")
    public String saveFormData(@RequestParam("file") MultipartFile file) {
        return this.documentService.saveFormData(file);
    }

    @ApiOperation("formData格式多个")
    @PostMapping("/formDates")
    public String saveFiles(@RequestParam("files") MultipartFile[] files) {
        String[] str = new String[files.length];
        int i = 0;
        for (MultipartFile file : files) {
            str[i++] = this.documentService.saveFormData(file);
        }
        return StringUtils.join(str, ",");
    }

    @ApiOperation("base64格式,formData提交数据")
    @PostMapping("/base64")
    public String saveBase64(@RequestParam("file") String file, @RequestParam("fileName") String fileName) {
        if (file.isEmpty()) {
            throw new ApiException("文件数据不能为空");
        }
        return this.documentService.saveBase64(file, fileName);
    }

    @ApiOperation("根据id查询")
    @GetMapping("/get/{id}")
    public Document getDocument(@PathVariable("id") String id) {
        return this.documentService.getDocument(id);
    }

    @ApiOperation("根据id查询多个文件")
    @GetMapping("/get/ids")
    public List<Document> getDocuments(@RequestParam("ids") String ids) {
        if ("".equals(ids)) {
            throw new ApiException("参数不能为空");
        }
        return this.documentService.getDocuments(ids);
    }

    @ApiOperation("删除文件")
    @DeleteMapping("/remove/{id}")
    public ApiResult<String> remove(@PathVariable("id") String id) {
        this.documentService.remove(id);
        return ApiResult.success();
    }

    @Autowired
    public void setDocumentService(DocumentService documentService) {
        this.documentService = documentService;
    }
}
